<template>
  <el-dialog
    title="提成比例"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    width="650px"
    :destroy-on-close="true"
    :close-on-click-modal="false">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      label-width="120px"
      style="width: 100%"
    >
      <el-form-item label="下级返佣：" prop="first_commission">
        <el-input placeholder="请输入内容" v-model="form.first_commission">
          <template slot="append">%</template>
        </el-input>
        <p class="warn-info">下级完成任务返佣=比例*任务金额</p>
      </el-form-item>
      <el-form-item label="下下级返佣：" prop="second_commission">
        <el-input placeholder="请输入内容" v-model="form.second_commission">
          <template slot="append">%</template>
        </el-input>
        <p class="warn-info">下下级完成任务返佣=比例*任务金额</p>
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex;justify-content: center;">
      <el-button type="primary"
                 @click="cancel">取消
      </el-button>
      <el-button type="primary"
                 @click="submit">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { commissionChange } from '../api'

export default {
  name: 'CommissionPercentage',
  data () {
    const validateCommission = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('必填'))
      }
      const v = parseFloat(value)
      if (Number.isNaN(v)) {
        callback(new Error('请输入数字'))
      } else {
        if (v < 0 || v > 100) {
          callback(new Error('请输入0-100间的数字'))
        } else {
          callback()
        }
      }
    }
    return {
      dialogVisible: false,
      form: {
        first_commission: '',
        second_commission: ''
      },
      rule: {
        first_commission: [
          { required: true, message: '请输入下级返佣' },
          { validator: validateCommission, trigger: 'blur' }
        ],
        second_commission: [
          { required: true, message: '请输入下下级返佣' },
          { validator: validateCommission, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleClose (done) {
      done()
    },
    open ({ id, first_commission, second_commission }) {
      this.id = id
      this.form = { first_commission, second_commission }
      this.dialogVisible = true
      return new Promise((resolve) => {
        this._resolve = resolve
      })
    },
    cancel () {
      this.close()
    },
    close () {
      this._resolve({ refresh: true })
      this.dialogVisible = false
    },
    async submit () {
      await this.$refs.form.validate()
      await commissionChange({ id: this.id }, this.form)
      this.$message.success('更新成功')
      this.close()
    }
  }
}
</script>

<style scoped lang="scss">
.warn-info {
  margin: 0;
  font-size: 12px;
  color: red;
}
</style>
